package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.system.entity.BtyArchives;
import cn.stylefeng.guns.sys.modular.system.entity.BtyYhkbg;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyYhkbgMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.UserMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyYhkbgParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyYhkbgResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyArchivesService;
import cn.stylefeng.guns.sys.modular.system.service.BtyBxdaService;
import cn.stylefeng.guns.sys.modular.system.service.BtyGufenzhuanrangService;
import cn.stylefeng.guns.sys.modular.system.service.BtyYhkbgService;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2021-06-08
 */
@Service
public class BtyYhkbgServiceImpl extends ServiceImpl<BtyYhkbgMapper, BtyYhkbg> implements BtyYhkbgService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private BtyBxdaService btyBxdaService;
    @Resource
    private BtyArchivesService archivesService;

    @Override
    public void add(BtyYhkbgParam param, String account){

        if (ToolUtil.isNotEmpty(account)){

            //申请人为当前登录者
            if (account.equals(param.getPhone())){

                //获取用户id
                Long userId = userMapper.getUserId(account);

                param.setStatus(1);//待审批
                param.setCreateUser(userId);
                BtyYhkbg entity = getEntity(param);
                this.save(entity);
            }
        }

    }

    @Override
    public void delete(BtyYhkbgParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyYhkbgParam param, String account){

        if (ToolUtil.isNotEmpty(account)){

            //获取当前数据的状态
            BtyYhkbgResult btyYhkbgResult = this.baseMapper.getById(param.getId());
            Integer sta = btyYhkbgResult.getStatus();

            //被驳回才可修改
            if (sta == 2){
                param.setStatus(1);//修改后状态改为待审核
                BtyYhkbg oldEntity = getOldEntity(param);
                BtyYhkbg newEntity = getEntity(param);
                ToolUtil.copyProperties(newEntity, oldEntity);
                this.updateById(newEntity);
            }
        }

    }

    @Override
    public BtyYhkbgResult findBySpec(BtyYhkbgParam param){
        return null;
    }

    @Override
    public List<BtyYhkbgResult> findListBySpec(BtyYhkbgParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyYhkbgParam param){
        Page pageContext = getPageContext();
       List<String> list= LoginContextHolder.getContext().getUser().getRoleNames();
        if(ToolUtil.isEmpty(param.getStatus())){
            param.setStatus(1);
        }
        if(list.contains("工资卡变更")&&list.contains("分红卡变更")){
            IPage page = this.baseMapper.customPageList(pageContext, param);
            return LayuiPageFactory.createPageInfo(page);
        }else if(list.contains("工资卡变更")){
            param.setYhkyt(1);
            IPage page = this.baseMapper.customPageList(pageContext, param);
            return LayuiPageFactory.createPageInfo(page);
        }else if(list.contains("分红卡变更")){
            param.setYhkyt(2);
            IPage page = this.baseMapper.customPageList(pageContext, param);
            return LayuiPageFactory.createPageInfo(page);
        }else{
            IPage page = this.baseMapper.customPageList(pageContext, param);
            return LayuiPageFactory.createPageInfo(page);
        }
    }

    private Serializable getKey(BtyYhkbgParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyYhkbg getOldEntity(BtyYhkbgParam param) {
        return this.getById(getKey(param));
    }

    private BtyYhkbg getEntity(BtyYhkbgParam param) {
        BtyYhkbg entity = new BtyYhkbg();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 银行卡审批
     * @param param
     * @param account
     */
    @Override
    public void approved(BtyYhkbgParam param, String account) {

        if (ToolUtil.isNotEmpty(account)){

            //查询当前数据的状态
            BtyYhkbgResult btyYhkbgResult = this.baseMapper.getById(param.getId());
            Integer sta = btyYhkbgResult.getStatus();

            //待审批状态才可审批
            if (sta == 1){

                //获取用户id
                Long userId = userMapper.getUserId(account);

                param.setUpdateUser(userId);

                BtyYhkbg btyYhkbg = getEntity(param);
                ToolUtil.copyProperties(btyYhkbg, param);
                this.baseMapper.updateById(btyYhkbg);


            }
        }
    }

    /**
     * 银行卡列表
     * @param param
     * @param account
     * @return
     */
    @Override
    public LayuiPageInfo yhkList(BtyYhkbgParam param, String account) {

        IPage page = null;
        if (ToolUtil.isNotEmpty(account)){
            Page pageContext = getPageContext();
            //获取用户id
            Long userId = userMapper.getUserId(account);
            param.setCreateUser(userId);
            param.setPhone(account);
            page = this.baseMapper.yhkList(pageContext, param);
        }
        return LayuiPageFactory.createPageInfo(page);
    }
    /**
     * 银行卡审批
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer confirmOk(Long id) {
        //通过id查询数据
        BtyYhkbg shenpi=baseMapper.selectOne(new QueryWrapper<BtyYhkbg>().eq("id",id));
        Integer status = shenpi.getStatus();
        if(ToolUtil.isNotEmpty(shenpi)&&status==1){
            shenpi.setStatus(3);
            shenpi.setUpdateTime(new Date());
            shenpi.setUpdateUser(LoginContextHolder.getContext().getUserId());
            baseMapper.updateById(shenpi);
        }else{
            return status;
        }
        return status;
    }
    /**
     * 银行卡驳回
     * @param btyYhkbgParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer bohui(BtyYhkbgParam btyYhkbgParam) {
        //通过id查询数据
        BtyYhkbg shenpi=baseMapper.selectOne(new QueryWrapper<BtyYhkbg>().eq("id",btyYhkbgParam.getId()));
        Integer status = shenpi.getStatus();
        if(ToolUtil.isNotEmpty(shenpi)&&status==1){
            //驳回状态
            shenpi.setStatus(2);
            //驳回原因
            if(ToolUtil.isNotEmpty(btyYhkbgParam.getReason())){
                shenpi.setReason(btyYhkbgParam.getReason());
            }
            shenpi.setUpdateTime(new Date());
            shenpi.setUpdateUser(LoginContextHolder.getContext().getUserId());
            baseMapper.updateById(shenpi);
        }else{
            return status;
        }
        return status;
    }

    /**
     * 银行卡详情
     * @param id
     * @return
     */
    @Override
    public List<Map> guyhkById(Long id) {
        return this.baseMapper.guyhkById(id);
    }

    /**
     * 银行卡列表(审核方)
     * @param param
     * @param account
     * @return
     */
    @Override
    public LayuiPageInfo yhkShList(BtyYhkbgParam param, String account) {

        if(ToolUtil.isNotEmpty(account)){
            //获取用户角色
            List<String> list = roleList(account);
            Page pageContext = getPageContext();
            if (list.contains("工资卡变更") && list.contains("分红卡变更")){
                IPage page = this.baseMapper.yhkShList(pageContext, param);
                return LayuiPageFactory.createPageInfo(page);
            }else if (list.contains("工资卡变更")){

                param.setYhkyt(1);
                IPage page = this.baseMapper.yhkShList(pageContext, param);
                return LayuiPageFactory.createPageInfo(page);
            }else if (list.contains("分红卡变更")){

                param.setYhkyt(2);
                IPage page = this.baseMapper.yhkShList(pageContext, param);
                return LayuiPageFactory.createPageInfo(page);
            }

        }

        LayuiPageInfo LayuiPageInfoNew = new LayuiPageInfo();
        LayuiPageInfoNew.setData(new ArrayList<BtyYhkbgResult>());
        return LayuiPageInfoNew;
//        return new LayuiPageInfo();
    }

    @Override
    public long queryAllDaibanQty(String account) {
        if(ToolUtil.isNotEmpty(account)){
            BtyYhkbgParam param = new BtyYhkbgParam();
            param.setStatus(1);
            //获取用户角色
            List<String> list = roleList(account);
            Page pageContext = getPageContext();
            if (list.contains("工资卡变更") && list.contains("分红卡变更")){
                IPage page = this.baseMapper.yhkShList(pageContext, param);
                return page.getTotal();
            }else if (list.contains("工资卡变更")){

                param.setYhkyt(1);
                IPage page = this.baseMapper.yhkShList(pageContext, param);
                return page.getTotal();
            }else if (list.contains("分红卡变更")){

                param.setYhkyt(2);
                IPage page = this.baseMapper.yhkShList(pageContext, param);
                return page.getTotal();
            }
        }
        return 0;
    }


    /**
     * 获取用户角色名称
     * @param account
     * @return
     */
    public List<String> roleList(String account){

        User user = null;
        //获取用户角色
        user = userMapper.getByAccount(account);
        if (ToolUtil.isEmpty(user)){
            user = userMapper.getAccount(account);
        }
        List<String> roleNames = new ArrayList<>();
        if (ToolUtil.isNotEmpty(user)){
            String userName = user.getName();//用户名字
            String roleId = user.getRoleId();//用户角色id
            String phone = user.getPhone();//用户电话
            List rolds = Arrays.asList(roleId.split(","));
            //获取用户角色名称
            roleNames = userMapper.getRole(rolds);
        }

        return roleNames;

    }

    /**
     * 审核通过的银行卡列表
     * @param account
     * @return
     */
    @Override
    public ResponseData yhkPassList(BtyYhkbgParam param, String account) {

        List<Map> list = new ArrayList<>();
        if (ToolUtil.isNotEmpty(account)){
            //获取用户id
            Long userId = userMapper.getUserId(account);
            param.setCreateUser(userId);
            param.setPhone(account);
//            list = this.baseMapper.yhkPassList(param);
            //获取工资卡信息
            list = this.baseMapper.yhkPassGz(param);
            List<Map> listFh = this.baseMapper.yhkPassFh(param);//获取分红卡信息
            list.addAll(listFh);
        }else {
            return ResponseData.error("电话不能为空！");
        }
        return ResponseData.success(list);
    }

    /**
     * 新增接口-app
     * @param param
     * @param account
     */
    @Override
    public ResponseData insert(BtyYhkbgParam param, String account) {

        //查询当前申请人是否有未存在的进程
        int sta = baseMapper.getSta(param.getPhone(), param.getYhkyt());
        if (sta != 0){
            return ResponseData.error(501, "该申请人存在尚未走完审批，不允许重复提交！");
        }

        //工资卡
        if (param.getYhkyt().equals(1)){
            //获取档案表原来银行卡号
            String yhk = archivesService.getYhkByBh(param.getBh());
            param.setYhkOld(yhk);
        }

        //获取提交申请用户id
        Long userId = userMapper.getUserId(account);
        param.setStatus(1);//待审批
        param.setCreateUser(userId);
        BtyYhkbg entity = getEntity(param);
        this.save(entity);
        return ResponseData.success();
    }

    /**
     * 判断当前登陆者角色接口-app
     * @param account
     * @return
     */
    @Override
    public ResponseData roleSta(String account) {
        Integer sta = 0;//不可修改姓名等信息

        List<String> list = roleList(account);
        if (list.contains("店长") || list.contains("大店长") || list.contains("督导") ||
                list.contains("营运经理") || list.contains("营运经理助理") || list.contains("营运总监")){

            sta = 1;//可以修改姓名等信息
        }
        return ResponseData.success(sta);
    }

    /**
     * 获取申请人信息接口-app
     * @param name
     * @param account
     * @return
     */
    @Override
    public List<Map> applicant(String name, String account) {
        List<Map> mapList = new ArrayList<>();
        if (ToolUtil.isNotEmpty(name)){
            mapList = this.baseMapper.applicant(name, null);
        }else if (ToolUtil.isNotEmpty(account)){
            mapList = this.baseMapper.applicant(null, account);
        }

        return mapList;
    }

    @Override
    public ResponseData updateApply(BtyYhkbgParam param) {

        //获取当前数据的状态
        BtyYhkbgResult btyYhkbgResult = this.baseMapper.getById(param.getId());
        Integer sta = btyYhkbgResult.getStatus();

        //被驳回才可修改
        if (sta == 2){
            param.setStatus(1);//修改后状态改为待审核
            BtyYhkbg oldEntity = getOldEntity(param);
            BtyYhkbg newEntity = getEntity(param);
            ToolUtil.copyProperties(newEntity, oldEntity);
            this.updateById(newEntity);
        }else {
            return ResponseData.error("被驳回状态才可修改！");
        }
        return ResponseData.success();
    }

    /**
     * 查看申请列表接口-app
     * @param param
     * @param account
     * @return
     */
    @Override
    public LayuiPageInfo applyList(BtyYhkbgParam param, String account) {

        IPage page = null;
        if (ToolUtil.isNotEmpty(account)){
            Page pageContext = getPageContext();
            //获取用户id
            Long userId = userMapper.getUserId(account);
            param.setCreateUser(userId);
            page = this.baseMapper.applyList(pageContext, param);
        }
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 校验银行卡信息-app
     * @param yhkNum
     * @return
     */
    @Override
    public ResponseData checkYhk(String yhkNum) {
        Integer sta = 0;//银行卡状态；0->异常，1->正常
        Map<String, Object> map = new HashMap<>();

        //通过银行卡号获取银行简称
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhkNum + "&cardBinCheck=true";
        String content = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(content);
        if (ToolUtil.isNotEmpty(jsonObject.get("bank"))){
            sta = 1;
            //银行简称
            String bank = jsonObject.get("bank").toString();
            //通过银行简称获取行号
            String code = btyBxdaService.getBankCode(bank);

            map.put("yhkNum", yhkNum);
            map.put("sta", sta);//银行卡状态；0->异常，1->正常
            map.put("bankCode", code);
            map.put("bank", bank);//银行简称
            return ResponseData.success(map);
        }else {
            map.put("sta", sta);//银行卡状态；0->异常，1->正常
            return ResponseData.success(map);
        }
    }

    /**
     * 工资卡初始化门店-PC
     * @return
     */
    @Override
    public ResponseData dmList() {
        List<String> list = archivesService.dmList();
        return ResponseData.success(list);
    }

    /**
     * 工资卡初始化营运经理-PC
     * @return
     */
    @Override
    public ResponseData yyjlList() {
        List<Map> list = archivesService.yyjlList();
        return ResponseData.success(list);
    }

    /**
     * 工资卡初始化督导-PC
     * @param yyjl
     * @return
     */
    @Override
    public ResponseData ddList(String yyjl) {
        List<Map> list = archivesService.ddList(yyjl);
        return ResponseData.success(list);
    }

    /**
     * 工资卡变更审核列表-PC
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo wagesList(BtyYhkbgParam param) {
        IPage page = null;
        Page pageContext = getPageContext();
        page = this.baseMapper.wagesList(pageContext, param);

        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 工资卡审批接口-PC
     * @param btyYhkbgParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData wagesApproved(BtyYhkbgParam btyYhkbgParam) {
        //通过id查询数据
        BtyYhkbg shenpi = baseMapper.selectOne(new QueryWrapper<BtyYhkbg>().eq("id",btyYhkbgParam.getId()));
        Integer status = shenpi.getStatus();
        //待审核状态才可修改
        if(ToolUtil.isNotEmpty(shenpi) && status == 1){
            //通过
            if (btyYhkbgParam.getStatus() == 3){
                if (ToolUtil.isNotEmpty(shenpi.getBh())){
                    BtyArchives btyArchives = new BtyArchives();
                    //钉钉编号
                    btyArchives.setBh(shenpi.getBh());
                    //新银行卡号
                    btyArchives.setYhk(shenpi.getYhkNum());
                    //新银行卡行号
                    btyArchives.setHh(shenpi.getBankCode());
                    //银行简称
                    btyArchives.setBank(shenpi.getBank());
                    //同步银行卡号及行号到档案表
                    archivesService.updateYhk(btyArchives);
                }
                //驳回
            }else if (btyYhkbgParam.getStatus() == 2){
                //驳回原因
                if(ToolUtil.isNotEmpty(btyYhkbgParam.getReason())){
                    shenpi.setReason(btyYhkbgParam.getReason());
                }
            }

            shenpi.setStatus(btyYhkbgParam.getStatus());
            shenpi.setUpdateTime(new Date());
            shenpi.setUpdateUser(LoginContextHolder.getContext().getUserId());
            //修改数据库状态
            baseMapper.updateById(shenpi);

            return ResponseData.success();
        }else {
            return ResponseData.error(201, "待审核状态才可审批！");
        }
    }

    /**
     * 分红卡变更审核列表-PC
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo bonusList(BtyYhkbgParam param) {
        IPage page = null;
        Page pageContext = getPageContext();
        page = this.baseMapper.bonusList(pageContext, param);

        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 分红卡审批接口-PC
     * @param btyYhkbgParam
     * @return
     */
    @Override
    public ResponseData bonusApproved(BtyYhkbgParam btyYhkbgParam) {
        //通过id查询数据
        BtyYhkbg shenpi = baseMapper.selectOne(new QueryWrapper<BtyYhkbg>().eq("id",btyYhkbgParam.getId()));
        Integer status = shenpi.getStatus();
        //待审核状态才可修改
        if(ToolUtil.isNotEmpty(shenpi) && status == 1){
                //驳回
            if (btyYhkbgParam.getStatus() == 2){
                //驳回原因
                if(ToolUtil.isNotEmpty(btyYhkbgParam.getReason())){
                    shenpi.setReason(btyYhkbgParam.getReason());
                }
            }
            shenpi.setStatus(btyYhkbgParam.getStatus());
            shenpi.setUpdateTime(new Date());
            shenpi.setUpdateUser(LoginContextHolder.getContext().getUserId());
            //修改数据库状态
            baseMapper.updateById(shenpi);

            return ResponseData.success();
        }else {
            return ResponseData.error(201, "待审核状态才可审批！");
        }
    }

    /**
     * 批量审批通过接口-PC
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData batchApproved(String ids, Integer yhkyt) {
        String id[] = ids.split(",");
        //银行卡用途;1->工资卡,2->分红卡
        if (yhkyt.equals(1)){
            //查询待审批的数据
            List<BtyYhkbg> list = baseMapper.getPending(id);
            if (ToolUtil.isNotEmpty(list)){
                for (BtyYhkbg yhkbg : list) {
                    if (ToolUtil.isNotEmpty(yhkbg.getBh())){
                        BtyArchives btyArchives = new BtyArchives();
                        //钉钉编号
                        btyArchives.setBh(yhkbg.getBh());
                        //新银行卡号
                        btyArchives.setYhk(yhkbg.getYhkNum());
                        //新银行卡行号
                        btyArchives.setHh(yhkbg.getBankCode());
                        //银行简称
                        btyArchives.setBank(yhkbg.getBank());
                        //同步银行卡号及行号到档案表
                        archivesService.updateYhk(btyArchives);
                    }
//                    yhkbg.setStatus(3);//审核状态,1->待审批，2->被驳回， 3->通过
//                    yhkbg.setUpdateTime(new Date());
//                    yhkbg.setUpdateUser(LoginContextHolder.getContext().getUserId());
//                    //修改数据库状态
//                    baseMapper.updateById(yhkbg);
                }
            }
        }

        //修改数据库状态
        baseMapper.updateByIds(id);

        return ResponseData.success();
    }
}
